package com.lmpop.frame.createEngine;

import com.lmpop.frame.SysMap;
import com.lmpop.frame.dao.DbmInterf;
import com.lmpop.frame.util.Config;
import com.lmpop.frame.util.DatebaseMgr;
import com.lmpop.frame.util.FileIO;
import com.lmpop.frame.util.InitProject;

import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;

public class CreateFile
{
  DatebaseMgr dbMgr;
  private Config config;
  private Config config_inst;
  static FileIO fileio;
  private static String biz_path;
  private String classPath;
  private String table_name;
  private String className;
  private String folder_path;
  private String classtem_path;
  private String jspTempaltePath;
  private String rootpath;
  private String jspSaveDir;
  private String createClass;
  private String createJsp;
  private String author;
  private String pri_key;
  private String trade_name;
  private String dbFieldName = "Field";
  private String dbFieldTypeName = "Type";
  private Hashtable fieldAttrMap;

  public CreateFile()
  {
    this.dbMgr = new DatebaseMgr();
    this.config = new Config();
    this.config_inst = new Config();
    this.rootpath = this.config.getString("rootpath");
    fileio = new FileIO();
    initClassPath();
    this.classtem_path = (this.rootpath + this.config_inst.getString("classtem_path"));
    biz_path = this.rootpath + this.config_inst.getString("biz_path");
    this.jspTempaltePath = (this.rootpath + this.config_inst.getString("jspTempaltePath"));
    this.fieldAttrMap = new Hashtable();
  }

  public void attrToMap(String fielddisattr) {
    String[] fieldAttr = fielddisattr.split(",");
    if (fieldAttr.length > 0)
      for (int i = 0; i < fieldAttr.length; i++)
        if (!fieldAttr[i].equals("")) {
          String[] oneAttr = fieldAttr[i].split("\\|");
          String key = ""; String value = "";
          if ((oneAttr.length > 1) && (!oneAttr[0].equals(""))) key = oneAttr[0];
          if (!key.equals("")) value = fieldAttr[i].replace(key + "|", "");
          this.fieldAttrMap.put(key, value);
        }
  }

  public String getFieldAttrValue(String fieldName, int num)
  {
    String fieldValue = ""; String resultVal = "";
    if ((this.fieldAttrMap != null) && (this.fieldAttrMap.get(fieldName) != null)) {
      fieldValue = this.fieldAttrMap.get(fieldName).toString();
    }
    if (!fieldValue.equals("")) {
      String[] fieldAttr = fieldValue.split("\\|");
      if (fieldAttr.length > num) resultVal = fieldAttr[num];
    }
    return resultVal;
  }

  public SysMap createFile(DbmInterf dbmMgr, SysMap map)
  {
    try
    {
      this.table_name = map.getString("table_name");
      this.pri_key = map.getString("pri_key");
      this.author = map.getString("author");
      this.jspSaveDir = map.getString("module_dir");

      this.createClass = map.getString("createClass");
      this.createJsp = map.getString("createJsp");

      String insert_bpmid = map.getString("insert_bpmid");
      String update_bpmid = map.getString("update_bpmid");
      String delete_bpmid = map.getString("delete_bpmid");
      String fielddisattr = map.getString("fielddisattr");
      this.trade_name = map.getString("trade_name");

      attrToMap(fielddisattr);

      System.out.println(this.fieldAttrMap + "=====================");

      this.folder_path = (biz_path + this.table_name);
      FileIO.CreateFloder(this.folder_path);
      if ((!this.table_name.equals("")) && (this.table_name.length() >= 1)) {
        this.className = (this.table_name.substring(0, 1).toUpperCase() + this.table_name.substring(1, this.table_name.length()));
      }
      if (this.createClass.equals("1")) {
        createPojo();
        createDao();
        createXml();

        createBuild();
      }
      if (this.createJsp.equals("1")) {
        createAddInfoJsp(insert_bpmid);
        createUpdateInfoJsp(update_bpmid);
        createIndexInfoJsp(delete_bpmid);
        createValidateJs();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return map;
  }

  public static void main(String[] args)
  {
    FileIO.LoadFile("D:/lilianglin_workspace/yiluo/WebRoot//WEB-INF/classes/javaTemplate/pojoTemplate.txt");
  }

  public void createPojo()
  {
    List fieldList = getTableDescList();

    String pojoString = FileIO.LoadFile(this.classtem_path + "pojoTemplate.txt");

    pojoString = replaceStrCommen(pojoString);

    StringBuffer pojoStr = new StringBuffer();

    if ((fieldList != null) && (fieldList.size() > 0)) {
      Hashtable fieldMap = new Hashtable();
      for (int i = 0; i < fieldList.size(); i++) {
        fieldMap = (Hashtable)fieldList.get(i);
        String Field = ""; String field_up = ""; String type_name = "";
        if (fieldMap.get(this.dbFieldName) != null) Field = fieldMap.get(this.dbFieldName).toString();
        if (fieldMap.get(this.dbFieldTypeName) != null) type_name = fieldMap.get(this.dbFieldTypeName).toString().toLowerCase();
        if ((!Field.equals("")) && (Field.length() >= 1)) {
          field_up = Field.substring(0, 1).toUpperCase() + Field.substring(1, Field.length());
        }
        String f_type = "String";
        if (type_name.indexOf("int") > -1) f_type = "int";
        pojoStr.append("\tprivate " + f_type + " " + Field + ";\n");
        pojoStr.append("\tpublic " + f_type + " get" + field_up + "() {\n");
        pojoStr.append("\t\treturn " + Field + ";\n");
        pojoStr.append("\t}\n");
        pojoStr.append("\tpublic void set" + field_up + "(" + f_type + " " + Field + ") {\n");
        pojoStr.append("\t\tthis." + Field + " = " + Field + ";\n");
        pojoStr.append("\t}\n");
      }
    }

    pojoString = pojoString.replace("#properties#", pojoStr.toString());

    FileIO.SaveToFile(pojoString, this.className + ".java", this.folder_path + "/");
  }

  public void createDao()
  {
    List fieldList = getTableDescList();

    String pojoString = FileIO.LoadFile(this.classtem_path + "daoTemplate.txt");
    pojoString = replaceStrCommen(pojoString);

    pojoString = pojoString.replace("#author#", this.author);
    pojoString = pojoString.replace("#createdate#", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));

    StringBuffer pojoStr = new StringBuffer();

    if ((fieldList != null) && (fieldList.size() > 0)) {
      Hashtable fieldMap = new Hashtable();
      for (int i = 0; i < fieldList.size(); i++) {
        fieldMap = (Hashtable)fieldList.get(i);
        String Field = ""; String field_up = ""; String type_name = "";
        if (fieldMap.get(this.dbFieldName) != null) Field = fieldMap.get(this.dbFieldName).toString();
        if (fieldMap.get(this.dbFieldTypeName) != null) type_name = fieldMap.get(this.dbFieldTypeName).toString().toLowerCase();
        if ((!Field.equals("")) && (Field.length() >= 1)) {
          field_up = Field.substring(0, 1).toUpperCase() + Field.substring(1, Field.length());
        }
        String f_type = "String";
        if (type_name.indexOf("int") > -1) f_type = "Int";
        pojoStr.append("\t\t" + this.table_name + ".set" + field_up + "(map.get" + f_type + "(\"" + Field + "\"));\n");
      }
    }

    pojoString = pojoString.replace("#setProperties#", pojoStr.toString());

    FileIO.SaveToFile(pojoString, this.className + "Info.java", this.folder_path + "/");
  }

  public void createXml()
  {
    List fieldList = getTableDescList();
    String fieldPk = this.pri_key;
    String pojoString = FileIO.LoadFile(this.classtem_path + "xmlTemplate.txt");
    pojoString = replaceStrCommen(pojoString);

    StringBuffer fieldStr = new StringBuffer();
    StringBuffer fieldVal = new StringBuffer();
    StringBuffer fieldUpdate = new StringBuffer();
    StringBuffer fieldCondition = new StringBuffer();

    if ((fieldList != null) && (fieldList.size() > 0)) {
      Hashtable fieldMap = new Hashtable();
      for (int i = 0; i < fieldList.size(); i++) {
        fieldMap = (Hashtable)fieldList.get(i);
        String Field = ""; String type_name = "";
        if (fieldMap.get(this.dbFieldName) != null) Field = fieldMap.get(this.dbFieldName).toString();
        if (fieldMap.get(this.dbFieldTypeName) != null) type_name = fieldMap.get(this.dbFieldTypeName).toString().toLowerCase();
        String signal = "#";
        if (type_name.indexOf("int") > -1) signal = "$";
        fieldStr.append(Field);
        fieldVal.append(signal + Field + signal);
        if (!fieldPk.equals(Field)) fieldUpdate.append(Field + "=" + signal + Field + signal);

        if (getFieldAttrValue(Field, 4).equals("0")) {
          fieldCondition.append("\t\t\t<isNotNull prepend=\"AND\" property=\"" + Field + "\">\n");
          fieldCondition.append("\t\t\t" + Field + " = " + signal + Field + signal + "\n");
          fieldCondition.append("\t\t\t</isNotNull>\n");
        }

        if (i == fieldList.size() - 1) {
          fieldStr.append("");
          fieldVal.append("");
          fieldUpdate.append("");
        } else {
          fieldStr.append(",");
          fieldVal.append(",");
          if (fieldPk.equals(Field)) continue; fieldUpdate.append(",");
        }
      }
    }

    pojoString = pojoString.replace("#fieldStr#", fieldStr.toString());
    pojoString = pojoString.replace("#fieldVal#", fieldVal.toString());
    pojoString = pojoString.replace("#fieldUpdate#", fieldUpdate.toString());
    pojoString = pojoString.replace("#fieldCondition#", fieldCondition.toString());

    FileIO.SaveToFile(pojoString, this.className + ".xml", this.folder_path + "/");
  }

  public void createBuild()
  {
    String pojoString = FileIO.LoadFile(this.classtem_path + "build.xml");
    pojoString = replaceStrCommen(pojoString);
    pojoString = pojoString.replace("#rootpath#", this.rootpath);
    FileIO.SaveToFile(pojoString, "build.xml", this.folder_path + "/");
  }

  public void createAddInfoJsp(String bpm_id)
  {
    List fieldList = getTableDescList();
    String pojoString = FileIO.LoadFile(this.jspTempaltePath + "addInfo.jsp");
    if (pojoString.equals("")) return;

    pojoString = replaceStrCommen(pojoString);

    String fieldlistTagName = "fieldlist";
    String fieldlistStart = "{" + fieldlistTagName + "}"; String fieldlistEnd = "{/" + fieldlistTagName + "}";
    String fieldlistAll = pojoString.substring(pojoString.indexOf(fieldlistStart), pojoString.indexOf(fieldlistEnd) + fieldlistEnd.length());
    String fieldlistBody = fieldlistAll.replace(fieldlistStart, "").replace(fieldlistEnd, "");

    StringBuffer fieldlisttagbody = new StringBuffer();

    if ((fieldList != null) && (fieldList.size() > 0)) {
      Hashtable fieldMap = new Hashtable();
      for (int i = 0; i < fieldList.size(); i++) {
        fieldMap = (Hashtable)fieldList.get(i);
        String Field = ""; String field_up = "";
        if (fieldMap.get(this.dbFieldName) != null) Field = fieldMap.get(this.dbFieldName).toString();
        if (!this.pri_key.equals(Field)) {
          String bodyTemp = fieldlistBody;
          String fieldcnname = Field;
          if (!getFieldAttrValue(Field, 1).equals("")) fieldcnname = getFieldAttrValue(Field, 1);
          bodyTemp = bodyTemp.replace("[fieldcnname/]", fieldcnname);
          String validateStr = ":";
          if (getFieldAttrValue(Field, 2).equals("0")) {
            validateStr = "<font color=\"red\">*</font>";
          }
          bodyTemp = bodyTemp.replace("[size/]", getFieldAttrValue(Field, 5));
          bodyTemp = bodyTemp.replace("[maxlength/]", getFieldAttrValue(Field, 6));
          bodyTemp = bodyTemp.replace("[validate/]", validateStr);
          bodyTemp = bodyTemp.replace("[fieldname/]", Field);
          fieldlisttagbody.append(bodyTemp);
        }
      }
    }
    pojoString = pojoString.replace(fieldlistAll, fieldlisttagbody.toString());
    pojoString = pojoString.replace("#bpm_id#", bpm_id);

    FileIO.SaveToFile(pojoString, "addInfo.jsp", this.rootpath + this.jspSaveDir);
  }

  public void createUpdateInfoJsp(String bpm_id)
  {
    List fieldList = getTableDescList();
    String pojoString = FileIO.LoadFile(this.jspTempaltePath + "updateInfo.jsp");
    if (pojoString.equals("")) return;

    pojoString = replaceStrCommen(pojoString);

    String fieldlistTagName = "fieldlist";
    String fieldlistStart = "{" + fieldlistTagName + "}"; String fieldlistEnd = "{/" + fieldlistTagName + "}";
    String fieldlistAll = pojoString.substring(pojoString.indexOf(fieldlistStart), pojoString.indexOf(fieldlistEnd) + fieldlistEnd.length());
    String fieldlistBody = fieldlistAll.replace(fieldlistStart, "").replace(fieldlistEnd, "");

    StringBuffer fieldlisttagbody = new StringBuffer();
    StringBuffer filedListname = new StringBuffer();
    StringBuffer filedListmap = new StringBuffer();

    if ((fieldList != null) && (fieldList.size() > 0)) {
      Hashtable fieldMap = new Hashtable();
      for (int i = 0; i < fieldList.size(); i++) {
        fieldMap = (Hashtable)fieldList.get(i);
        String Field = ""; String field_up = "";
        if (fieldMap.get(this.dbFieldName) != null) Field = fieldMap.get(this.dbFieldName).toString();
        if (!Field.equals(this.pri_key)) {
          String bodyTemp = fieldlistBody;
          String fieldcnname = Field;
          if (!getFieldAttrValue(Field, 1).equals("")) fieldcnname = getFieldAttrValue(Field, 1);
          bodyTemp = bodyTemp.replace("[fieldcnname/]", fieldcnname);
          String validateStr = ":";
          if (getFieldAttrValue(Field, 2).equals("0")) {
            validateStr = "<font color=\"red\">*</font>";
          }
          bodyTemp = bodyTemp.replace("[validate/]", validateStr);
          bodyTemp = bodyTemp.replace("[size/]", getFieldAttrValue(Field, 5));
          bodyTemp = bodyTemp.replace("[maxlength/]", getFieldAttrValue(Field, 6));
          bodyTemp = bodyTemp.replace("[fieldname/]", Field);
          fieldlisttagbody.append(bodyTemp);
          filedListname.append(Field + "=\"\"");
          if (i != fieldList.size() - 1) filedListname.append(",");
          filedListmap.append("  \tif(map.get(\"" + Field + "\")!=null) " + Field + " = map.get(\"" + Field + "\").toString();\n");
        }
      }
    }

    pojoString = pojoString.replace(fieldlistAll, fieldlisttagbody.toString());
    pojoString = pojoString.replace("#bpm_id#", bpm_id);
    pojoString = pojoString.replace("#filedListmap#", filedListmap.toString());
    pojoString = pojoString.replace("#fieldlistname#", filedListname.toString());

    FileIO.SaveToFile(pojoString, "updateInfo.jsp", this.rootpath + this.jspSaveDir);
  }

  public void createIndexInfoJsp(String bpm_id)
  {
    List fieldList = getTableDescList();
    String fieldPk = this.pri_key;

    String pojoString = FileIO.LoadFile(this.jspTempaltePath + "index.jsp");
    if (pojoString.equals("")) return;

    pojoString = replaceStrCommen(pojoString);

    pojoString = replaceNoonByTag(pojoString, "fieldlist", fieldList);
    pojoString = replaceNoonByTag(pojoString, "searchlist", fieldList);

    StringBuffer filedListname = new StringBuffer();
    StringBuffer filedListmap = new StringBuffer();

    if ((fieldList != null) && (fieldList.size() > 0)) {
      Hashtable fieldMap = new Hashtable();
      for (int i = 0; i < fieldList.size(); i++) {
        fieldMap = (Hashtable)fieldList.get(i);
        String Field = ""; String type_name = "";
        if (fieldMap.get(this.dbFieldName) != null) Field = fieldMap.get(this.dbFieldName).toString();
        if (fieldMap.get(this.dbFieldTypeName) != null) type_name = fieldMap.get(this.dbFieldTypeName).toString().toLowerCase();
        filedListname.append(Field + "=\"\"");
        if (i != fieldList.size() - 1) filedListname.append(",");
        filedListmap.append("  \tif(map.get(\"" + Field + "\")!=null) " + Field + " = map.get(\"" + Field + "\").toString();\n");
        if (type_name.equals("datetime")) {
          filedListmap.append("if(" + Field + ".length()>19)" + Field + "=" + Field + ".substring(0,19);\n");
        }
      }
    }

    pojoString = pojoString.replace("#bpm_id#", bpm_id);
    pojoString = pojoString.replace("#filedListmap#", filedListmap.toString());
    pojoString = pojoString.replace("#fieldlistname#", filedListname.toString());

    FileIO.SaveToFile(pojoString, "index.jsp", this.rootpath + this.jspSaveDir);
  }

  public String replaceNoonByTag(String pojoString, String tagName, List fieldList)
  {
    String fieldlistTagName = tagName;
    while (pojoString.indexOf("{" + fieldlistTagName + "}") > -1) {
      StringBuffer fieldlisttagbody = new StringBuffer();
      String fieldlistStart = "{" + fieldlistTagName + "}"; String fieldlistEnd = "{/" + fieldlistTagName + "}";
      String fieldlistAll = pojoString.substring(pojoString.indexOf(fieldlistStart), pojoString.indexOf(fieldlistEnd) + fieldlistEnd.length());
      String fieldlistBody = fieldlistAll.replace(fieldlistStart, "").replace(fieldlistEnd, "");
      if ((fieldList != null) && (fieldList.size() > 0)) {
        Hashtable fieldMap = new Hashtable();
        for (int i = 0; i < fieldList.size(); i++) {
          fieldMap = (Hashtable)fieldList.get(i);
          String Field = ""; String field_up = "";
          if (fieldMap.get(this.dbFieldName) != null) Field = fieldMap.get(this.dbFieldName).toString();
          String fieldcnname = Field;
          if (!getFieldAttrValue(Field, 1).equals("")) fieldcnname = getFieldAttrValue(Field, 1);
          if ((getFieldAttrValue(Field, 0).equals("1")) || 
            ((tagName.equals("searchlist")) && (getFieldAttrValue(Field, 4).equals("1"))) || 
            (Field.equals(this.pri_key))) continue;
          String bodyTemp = fieldlistBody;
          bodyTemp = bodyTemp.replace("[fieldcnname/]", fieldcnname);
          bodyTemp = bodyTemp.replace("[fieldname/]", Field);
          fieldlisttagbody.append(bodyTemp);
        }
      }

      pojoString = pojoString.replace(fieldlistAll, fieldlisttagbody.toString());
    }
    return pojoString;
  }

  public void createValidateJs()
  {
    List fieldList = getTableDescList();
    String pojoString = FileIO.LoadFile(this.jspTempaltePath + "index.js");
    if (pojoString.equals("")) return;

    pojoString = replaceStrCommen(pojoString);

    String fieldlistTagName = "fieldlist";
    String fieldlistStart = "{" + fieldlistTagName + "}"; String fieldlistEnd = "{/" + fieldlistTagName + "}";
    String fieldlistAll = pojoString.substring(pojoString.indexOf(fieldlistStart), pojoString.indexOf(fieldlistEnd) + fieldlistEnd.length());
    String fieldlistBody = fieldlistAll.replace(fieldlistStart, "").replace(fieldlistEnd, "");

    StringBuffer fieldlisttagbody = new StringBuffer();

    if ((fieldList != null) && (fieldList.size() > 0)) {
      Hashtable fieldMap = new Hashtable();
      for (int i = 0; i < fieldList.size(); i++) {
        fieldMap = (Hashtable)fieldList.get(i);
        String Field = "";
        if (fieldMap.get(this.dbFieldName) != null) Field = fieldMap.get(this.dbFieldName).toString();
        if (!getFieldAttrValue(Field, 2).equals("1")) {
          String bodyTemp = fieldlistBody;
          bodyTemp = bodyTemp.replace("[validatename/]", getFieldAttrValue(Field, 3));
          bodyTemp = bodyTemp.replace("[fieldname/]", Field);
          fieldlisttagbody.append(bodyTemp);
        }
      }
    }
    pojoString = pojoString.replace(fieldlistAll, fieldlisttagbody.toString());

    FileIO.SaveToFile(pojoString, "index.js", this.rootpath + this.jspSaveDir);
  }

  public String replaceStrCommen(String strTemp) {
    strTemp = strTemp.replace("#table_name#", this.table_name);
    strTemp = strTemp.replace("#className#", this.className);
    strTemp = strTemp.replace("#pk#", this.pri_key);
    strTemp = strTemp.replace("#trade_name#", this.trade_name);
    return strTemp;
  }

  public void insertMapConfig()
  {
    String sqlMapConfigPath = this.rootpath + this.config_inst.getString("sqlMapConfigPath");
    String sqlMapConfigName = this.config_inst.getString("sqlMapConfigName");
    String package_name = this.config_inst.getString("package_name");
    String sqlMapFilePath = sqlMapConfigPath + sqlMapConfigName;
    String pojoString = FileIO.LoadFile(sqlMapFilePath);
    String xmlPath = package_name + this.table_name + "/" + this.className + ".xml";
    String tagname = "<!--bizmaps-->";
    String xmlPathString = "<sqlMap resource=\"" + xmlPath + "\" />";
    if (pojoString.indexOf(xmlPath) == -1) {
      pojoString = pojoString.replace(tagname, tagname + "\n" + xmlPathString);
    }
    FileIO.SaveToFile(pojoString, sqlMapConfigName, sqlMapConfigPath);
  }

  public void initClassPath()
  {
    this.classPath = InitProject.classPath();
  }

  public List getTableDescList()
  {
    return this.dbMgr.getTableDescList(this.table_name);
  }
}